import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/',
    redirect: '/dashboard',
    component: () => import('@/layout/MainLayout.vue'),
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '首页', icon: 'HomeFilled' }
      },
      {
        path: '/common',
        name: 'Common',
        meta: { title: '常用', icon: 'Star' },
        children: [
          {
            path: '/common/reports',
            name: 'CommonReports',
            component: () => import('@/views/common/Reports.vue'),
            meta: { title: '常用报表', icon: 'Document' }
          }
        ]
      },
      {
        path: '/report',
        name: 'Report',
        redirect: '/report/customer-analysis',
        meta: { title: '报表', hidden: true },
        children: [
          {
            path: '/report/customer-analysis',
            name: 'CustomerAnalysis',
            component: () => import('@/views/report/CustomerAnalysis.vue'),
            meta: { title: '客单分析', icon: 'DataAnalysis' }
          },
              {
                path: '/report/supplier-profile',
                name: 'SupplierProfile',
                component: () => import('@/views/report/SupplierProfile.vue'),
                meta: { title: '供应商档案', icon: 'Document' }
              },
              {
                path: '/report/contract-expense',
                name: 'ContractExpense',
                component: () => import('@/views/report/ContractExpense.vue'),
                meta: { title: '合同费用明细', icon: 'Coin' }
              }
        ]
      },
      {
        path: '/basic',
        name: 'Basic',
        meta: { title: '基础信息', icon: 'Files' },
        children: [
          {
            path: '/basic/ingredient',
            name: 'Ingredient',
            component: () => import('@/views/basic/Ingredient.vue'),
            meta: { title: '配料信息', icon: 'Bowl' }
          }
        ]
      },
      {
        path: '/system',
        name: 'System',
        meta: { title: '系统设置', icon: 'Setting' },
        children: [
          {
            path: '/system/database',
            name: 'Database',
            component: () => import('@/views/system/Database.vue'),
            meta: { title: '数据库管理', icon: 'DataLine' }
          }
        ]
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  if (to.path === '/login') {
    next()
  } else {
    if (token) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router


